﻿using System;    
using LiteNetLib;               
using Lockstep.Network.Client;

/// <summary>
/// 客户端网络通信处理模块
/// 功能：
/// 1. 连接
/// 2. 发送
/// 3. 接收
/// 4. 断开
/// </summary>
public class LiteNetLibClient : INetwork
{
    private readonly EventBasedNetListener _listener = new EventBasedNetListener();
    //                                          
    private NetManager _client;
    /// <summary>
    /// 接收回调
    /// </summary>
    public event Action<byte[]> DataReceived;

    public bool Connected => _client.FirstPeer?.ConnectionState == ConnectionState.Connected;       

    public void Start()
    {
        //接收处理
        _listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) =>
        {
            DataReceived?.Invoke(dataReader.GetRemainingBytes());
            dataReader.Recycle();
        };

        _client = new NetManager(_listener)
        {
            DisconnectTimeout = 30000
        };
        _client.Start();
    }

    /// <summary>
    /// 连接
    /// </summary>
    /// <param name="serverIp"></param>
    /// <param name="port"></param>
    public void Connect(string serverIp, int port)
    {
        _client.Connect(serverIp, port, "SomeConnectionKey");
    }

    /// <summary>
    /// 发送
    /// </summary>
    /// <param name="data"></param>
    public void Send(byte[] data)
    {
        _client.FirstPeer.Send(data, DeliveryMethod.ReliableOrdered);
    }
        
    public void Update()
    {    
        _client.PollEvents();
    }    

    public void Stop()
    {
        _client.Stop();
    }
}
